package com.example.epidemic_assistant.ui;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.epidemic_assistant.gen.DaoSession;
import com.android.epidemic_assistant.gen.UserBeanDao;
import com.example.epidemic_assistant.App;
import com.example.epidemic_assistant.BaseActivity;
import com.example.epidemic_assistant.R;
import com.example.epidemic_assistant.bean.UserBean;
import com.example.epidemic_assistant.ui.adapter.PeopleAdapter;
import com.example.epidemic_assistant.ui.adapter.PlaceAdapter;
import com.example.epidemic_assistant.util.FileUtil;
import com.example.epidemic_assistant.weiget.MyMarkerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Utils;

import java.util.ArrayList;
import java.util.List;

public class UserManagerDetailsActivity extends BaseActivity implements PlaceAdapter.IDeleteClick
        , PeopleAdapter.IDeleteClick, OnChartValueSelectedListener {

    private final static String TAG = "UserManagerDetailsActivity";

    private TextView mTvDay;
    private TextView mTvAge;
    private TextView mTvSex;
    private TextView mTvIdCard;
    private TextView mTvAddress;
    private ImageView mImgHealth;
    private ImageView mImgHealthMa;
    private RecyclerView mRvPlace;
    private RecyclerView mRvPeople;
    private LineChart chart;

    private PlaceAdapter mPlaceAdapter;
    private PeopleAdapter mPeopleAdapter;

    private ArrayList<String> mPlaceList = new ArrayList<>();
    private ArrayList<String> mPeopleList = new ArrayList<>();
    private ArrayList<String> mTemperatureList = new ArrayList<>();


    private App mMyApp;
    private DaoSession mDaoSession;
    private UserBeanDao mUserBeanDao;
    private List<UserBean> mUserBeans;

    private List<UserBean> mUserBeanList;
    private List<Integer> mRoomIdList;
    private UserBean mUserBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_manager_details);

        initView();
        initData();
        initListener();
    }

    private void initListener() {

    }

    private void initData() {
        Bundle extras = getIntent().getExtras();
        int position = extras.getInt("position");

        mMyApp = (App) this.getApplication();
        mDaoSession = mMyApp.getDaoSession();
        mUserBeanDao = mDaoSession.getUserBeanDao();
        mUserBeans = mUserBeanDao.loadAll();

        mUserBeanList = new ArrayList<>();
        mRoomIdList = new ArrayList<>();

        for (UserBean userBean : mUserBeans) {
            if (!userBean.isAdmin() && !mRoomIdList.contains(userBean.getRoomId()) ) {
                mUserBeanList.add(userBean);
                mRoomIdList.add(userBean.getRoomId());
            }
        }

        mUserBean = mUserBeanList.get(position);

        mTvDay.setText(String.valueOf(mUserBean.getDay()));
        mTvAge.setText(mUserBean.getAge());
        mTvSex.setText(mUserBean.getSex());
        mTvIdCard.setText(mUserBean.getIdCard());
        mTvAddress.setText(mUserBean.getFamilyAddress());
        mImgHealth.setImageBitmap(FileUtil.ImagePathToBitmap(mUserBean.getHealthImgPath()));
        mImgHealthMa.setImageBitmap(FileUtil.ImagePathToBitmap(mUserBean.getHealthMaImgPath()));
        if (mUserBean.getPlaces() != null) {
            for (int i = 0; i < mUserBean.getPlaces().size(); i++) {
                String s = mUserBean.getPlaces().get(i);
                if (!s.isEmpty()) {
                    mPlaceList.add(s);
                }
            }
        }
        if (mUserBean.getPeople() != null) {
            for (int i = 0; i < mUserBean.getPeople().size(); i++) {
                String s = mUserBean.getPeople().get(i);
                if (!s.isEmpty()) {
                    mPeopleList.add(s);
                }
            }
        }
        if (mUserBean.getTemperature() != null) {
            for (int i = 0; i < mUserBean.getTemperature().size(); i++) {
                String s = mUserBean.getTemperature().get(i);
                if (!s.isEmpty()) {
                    mTemperatureList.add(s);
                }
            }
        }
        initChart();

        //去过的地方
        mRvPlace.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mPlaceAdapter = new PlaceAdapter(this, mPlaceList);
        mPlaceAdapter.setOnDeleteClick(this);
        mRvPlace.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mRvPlace.setAdapter(mPlaceAdapter);

        //接触过的人
        mRvPeople.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mPeopleAdapter = new PeopleAdapter(this,  mPeopleList);
        mPeopleAdapter.setOnPeopleDeleteClick(this);
        mRvPeople.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mRvPeople.setAdapter(mPeopleAdapter);
    }

    private void initChart() {
        // background color
        chart.setBackgroundColor(Color.WHITE);

        // disable description text
        chart.getDescription().setEnabled(false);

        // enable touch gestures
        chart.setTouchEnabled(true);

        // set listeners
        chart.setOnChartValueSelectedListener(this);
        chart.setDrawGridBackground(false);

        // create marker to display box when values are selected
        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);

        // Set the marker to the chart
        mv.setChartView(chart);
        chart.setMarker(mv);

        // enable scaling and dragging
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        // chart.setScaleXEnabled(true);
        // chart.setScaleYEnabled(true);

        // force pinch zoom along both axis
        chart.setPinchZoom(true);

        // draw points over time
        chart.animateX(1500);

        // get the legend (only possible after setting data)
        Legend l = chart.getLegend();

        // draw legend entries as lines
        l.setForm(Legend.LegendForm.LINE);

        ArrayList<Entry> values = new ArrayList<>();

        if (mTemperatureList != null) {
            for (int i = 0; i < mTemperatureList.size(); i++) {
                values.add(new Entry(i, Float.parseFloat(mTemperatureList.get(i)), getResources().getDrawable(R.drawable.star)));

            }
        }

        LineDataSet set1;
        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            set1.notifyDataSetChanged();
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values, "Temperature List");

            set1.setDrawIcons(false);

            // draw dashed line
            set1.enableDashedLine(10f, 5f, 0f);

            // black lines and points
            set1.setColor(Color.BLACK);
            set1.setCircleColor(Color.BLACK);

            // line thickness and point size
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);

            // draw points as solid circles
            set1.setDrawCircleHole(false);

            // customize legend entry
            set1.setFormLineWidth(1f);
            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);

            // text size of values
            set1.setValueTextSize(9f);

            // draw selection line as dashed
            set1.enableDashedHighlightLine(10f, 5f, 0f);

            // set the filled area
            set1.setDrawFilled(true);
            set1.setFillFormatter((dataSet, dataProvider) -> chart.getAxisLeft().getAxisMinimum());

            // set color of filled area
            if (Utils.getSDKInt() >= 18) {
                // drawables only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_red);
                set1.setFillDrawable(drawable);
            } else {
                set1.setFillColor(Color.BLACK);
            }

            ArrayList<ILineDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1); // add the data sets

            // create a data object with the data sets
            LineData data = new LineData(dataSets);

            // set data
            chart.setData(data);
        }
    }

    private void initView() {
        mTvDay = findViewById(R.id.tv_day);
        mImgHealth = findViewById(R.id.img_health);
        mImgHealthMa = findViewById(R.id.img_health_ma);
        mRvPlace = findViewById(R.id.rv_place);
        mRvPeople = findViewById(R.id.rv_people);
        mTvAge = findViewById(R.id.tv_age);
        mTvSex = findViewById(R.id.tv_sex);
        mTvIdCard = findViewById(R.id.tv_id_card);
        mTvAddress = findViewById(R.id.tv_address);
        chart = findViewById(R.id.chart_temperature);
    }

    @Override
    public void onPeopleDeleteClick(int position) {
        //接触过的人删除
        mPeopleList.remove(position);
        mPeopleAdapter.notifyDataSetChanged();
        mUserBean.setPeople(mPeopleList);
        mUserBeanDao.update(mUserBean);
    }

    @Override
    public void onDeleteClick(int position) {
        //去过的地方删除
        mPlaceList.remove(position);
        mPlaceAdapter.notifyDataSetChanged();
        mUserBean.setPlaces(mPlaceList);
        mUserBeanDao.update(mUserBean);
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }
}